<template>
  <div class="publish-button">
    <el-button type="primary" class="publish-btn" @click="showDialog = true">发布</el-button>

    <!-- 发布弹窗 -->
    <el-dialog
      v-model="showDialog"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="农产品名称" prop="product_name">
          <el-input v-model="formData.product_name" placeholder="请输入产品名称" />
        </el-form-item>

        <el-form-item label="分类" prop="product_category">
          <el-select v-model="formData.product_category" placeholder="请选择分类">
            <el-option label="水果类" value="水果" />
            <el-option label="蔬菜类" value="蔬菜" />
            <el-option label="粮食类" value="粮食" />
            <el-option label="禽蛋类" value="禽蛋" />
            <el-option label="乳制品" value="乳制品" />
          </el-select>
        </el-form-item>

        <el-form-item label="地区" prop="region">
          <el-input v-model="formData.region" placeholder="请输入地区" />
        </el-form-item>

        <el-form-item :label="type === 'buy' ? '收购总量(斤)' : '出售总量(斤)'" prop="total_quantity">
          <el-input-number 
            v-model="formData.total_quantity" 
            :min="0"
            :precision="2"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item :label="priceLabel" prop="price_offer">
          <el-input-number 
            v-model="formData.price_offer"
            :min="0"
            :precision="2"
            :step="0.5"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="截止时间" prop="deadline">
          <el-date-picker
            v-model="formData.deadline"
            type="datetime"
            placeholder="选择截止时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handlePublish" :loading="publishing">发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { inject } from 'vue'

const $axios = inject('$axios')

const props = defineProps({
  type: {
    type: String,
    required: true,
    validator: (value) => ['buy', 'sell'].includes(value)
  }
})

const emit = defineEmits(['publish'])

const showDialog = ref(false)
const formRef = ref(null)
const publishing = ref(false)

// 表单数据
const formData = reactive({
  product_name: '',
  product_category: '',
  region: '',
  total_quantity: 0,
  price_offer: 0,
  deadline: '',
  content: ''
})

// 表单验证规则
const rules = {
  product_name: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  product_category: [
    { required: true, message: '请选择产品分类', trigger: 'change' }
  ],
  region: [
    { required: true, message: '请输入地区', trigger: 'blur' }
  ],
  total_quantity: [
    { required: true, message: '请输入总量', trigger: 'blur' },
    { type: 'number', min: 0, message: '总量必须大于0', trigger: 'blur' }
  ],
  price_offer: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于0', trigger: 'blur' }
  ],
  deadline: [
    { required: true, message: '请选择截止时间', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 10, max: 1000, message: '长度在 10 到 1000 个字符', trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => 
  props.type === 'buy' ? '发布收购公告' : '发布出售公告'
)

const priceLabel = computed(() => 
  props.type === 'buy' ? '收购价格(元/斤)' : '出售价格(元/斤)'
)

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 处理弹窗关闭
const handleDialogClose = (done) => {
  if (
    formData.product_name ||
    formData.product_category ||
    formData.region ||
    formData.total_quantity > 0 ||
    formData.price_offer > 0 ||
    formData.deadline ||
    formData.content
  ) {
    ElMessageBox.confirm('确认关闭？输入的内容将会丢失', '', {
      confirmButtonText: '好的',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        formRef.value?.resetFields()
        showDialog.value = false
        if (typeof done === 'function') {
          done()
        }
      })
      .catch(() => {})
  } else {
    showDialog.value = false
    if (typeof done === 'function') {
      done()
    }
  }
}

// 处理发布
const handlePublish = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    publishing.value = true
    
    // 构造请求数据
    const postData = {
      title: `${formData.product_name}${props.type === 'buy' ? '收购' : '出售'}公告`,
      content: formData.content,
      product_name: formData.product_name,
      product_category: formData.product_category,
      price_offer: formData.price_offer.toString(), // 转为字符串
      total_quantity: formData.total_quantity.toString(), // 转为字符串
      remaining_quantity: formData.total_quantity.toString(), // 初始剩余量等于总量
      region: formData.region,
      deadline: formData.deadline
    }

    // 发送请求
    const response = await $axios.post('/article', postData, {
      headers: {
        'Authorization': localStorage.getItem('token') // 从本地存储获取token
      }
    })

    if (response.data.code === 200) {
      console.log(response.data)
      // 发布成功
      ElMessage.success('发布成功')
      emit('publish') // 触发发布
      showDialog.value = false
      formRef.value.resetFields()
    } else {
      // 发布失败
      ElMessage.error(response.data.msg || '发布失败')
    }
  } catch (error) {
    console.error('发布失败：', error)
    if (error.response) {
      // 处理后端返回的错误
      ElMessage.error(error.response.data.msg || '发布失败，请检查网络连接')
    } else {
      // 处理其他错误
      ElMessage.error('请检查表单内容或网络连接')
    }
  } finally {
    publishing.value = false
  }
}
</script>

<style lang="less" scoped>
.publish-button {
  .publish-btn {
    background: #409eff;
  }
}

:deep(.el-dialog) {
  .el-dialog__body {
    padding: 20px 40px;
  }
}

@media screen and (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    
    .el-dialog__body {
      padding: 20px;
    }
  }
}
</style>